#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
密码管理器。目前之做了一部分功能，保存和加密还没有做。
'''
__author__ = 'chenwei'
__version__ = 'v1.0.0'
import pickle
import random

def open_file(fn, md='rb'):  # 打开文件函数
    try:
        return open(fn, md)
    except IOError as e:
        raise e


def load_pickle(fn):#读取序列化文件。
    with open_file(fn) as f:
        try:
            return pickle.load(f)
        except EOFError as e:
            pass
        except Exception as e:
            raise e


def dump_pickle(pkl_item,fn):#保存序列化文件。
    with open_file(fn, md='w+b') as f:
        try:
            pickle.dump(pkl_item, f)
        except Exception as e:
            raise e
    return True

def myAlign(string, length=0,placeholder= ' ',head=False,head_placeholder= ' ',tail=False,tail_placeholder= ' '):
    if length == 0:
        return string
    slen= len(string)
    re = string
    flag = False
    while slen < length-2:
        flag = True
        if slen % 2 == 0:
            re += placeholder
        else:
            re = placeholder + re
        slen += 1
    if head:
        re = head_placeholder + re
    elif flag:
        re = placeholder + re
    if tail:
        re += tail_placeholder
    elif flag:
        re += placeholder
    return re

def generate_verification_code(len=10):
    ''' 随机生成X位的验证码 '''
    # 注意： 这里我们生成的是0-9A-Za-z的列表，当然你也可以指定这个list，这里很灵活
    # 比如： code_list = ['P','y','t','h','o','n','T','a','b'] # PythonTab的字母
    code_list = []
    for i in range(10): # 0-9数字
        code_list.append(str(i))
    for i in range(65, 91): # 对应从“A”到“Z”的ASCII码
        code_list.append(chr(i))
    for i in range(97, 123): #对应从“a”到“z”的ASCII码
        code_list.append(chr(i))
    code_list.append('@')
    code_list.append('#')
    code_list.append('$')
    myslice = random.sample(code_list, len)  # 从list中随机获取6个元素，作为一个片断返回
    verification_code = ''.join(myslice) # list to string
    return verification_code


class passwd_manager(dict):
    def __init__(self):
        super().__init__()
        self.data = {}
        self.catagory = ''
    def insert_data(self,tittle,username,password,url):
        self.data[tittle] = [username, password, url]
    def modify_data(self,tittle,username,password,url):
        self.data[tittle] = [username, password, url]
    def del_data(self,tittle):
        try:
            del self.data[tittle]
        except KeyError as e:
            return False
    def find_data(self,tittle):
        tmp={}
        for key in self.data.keys():
            if tittle in key:
                tmp[key]=self.data[key]
        if tmp == {}:
            print('Not Found!')
            return False
        self.print_dict(obj=tmp.items())
    def print_dict(self,obj='',col_1='tittle', col_2='username', col_3='password', col_4='url'):
        if obj == '':
            obj = self.data.items()
        print(myAlign(self.catagory,100))#表头的输出
        print(myAlign(col_1,20,'-',head=True,head_placeholder='+')\
              + myAlign(col_2,20,'-',head=True,head_placeholder='+')\
              + myAlign(col_3,20,'-',head=True,head_placeholder='+')\
              + myAlign(col_4,40,'-',head=True,head_placeholder='+',tail=True,tail_placeholder='+'))#格式化输出报表头
        for key,value in obj:
            print(myAlign(key,20,' ',head=True,head_placeholder='|') \
                  + myAlign(value[0], 20, ' ', head=True, head_placeholder='|') \
                  + myAlign(value[1], 20, ' ', head=True, head_placeholder='|') \
                  + myAlign(value[2], 40, ' ', head=True, head_placeholder='|',tail=True,tail_placeholder='|'))#循环输出
        print(myAlign('',100,'-',head=True,head_placeholder='+',tail=True,tail_placeholder='+'))


class web_passwd_manager(passwd_manager):
    def __init__(self):
        super().__init__()
        self.data = {}
        self.catagory = 'web'
    def print_all(self):
        self.print_dict()
class bank_passwd_manager(passwd_manager):
    def __init__(self):
        super().__init__()
        self.data = {}
        self.catagory = 'bank'
    def print_all(self):
        self.print_dict()
class server_passwd_manager(passwd_manager):
    def __init__(self):
        super().__init__()
        self.data = {}
        self.catagory = 'server'
    def print_all(self,col_4='ip:port'):
        self.print_dict(col_4=col_4)
class app_passwd_manager(passwd_manager):
    def __init__(self):
        super().__init__()
        self.data = {}
        self.catagory = 'app'
    def print_all(self):
        self.print_dict()


if __name__ == '__main__':
    web = web_passwd_manager()
    bank = bank_passwd_manager()
    app = app_passwd_manager()
    server = server_passwd_manager()
    web.insert_data('test1', 'ce', 'cw', 'http://www.baidu.com')
    web.insert_data('test2','ce','cw','http://www.baidu.com')
    bank.insert_data('test1', 'ce', 'cw', 'http://www.baidu.com')
    bank.insert_data('test2','ce','cw','http://www.baidu.com')
    app.insert_data('test1', 'ce', 'cw', 'http://www.baidu.com')
    app.insert_data('test2','ce','cw','http://www.baidu.com')
    server.insert_data('test1', 'ce', 'cw', 'http://www.baidu.com')
    server.insert_data('test2','ce','cw','http://www.baidu.com')
    web.find_data('test11')
    web.print_all()
    bank.print_all()
    server.print_all()
    app.print_all()
    passwd = generate_verification_code(15)
    print(passwd)

